#!/usr/bin/env python
# encoding: utf-8

import hashlib,time,random,decimal,json

from app import db
from app.model import User
from app.model import Electronic
from app.common.libs.Helper import getCurrentDate

class ElectronicService():

    @staticmethod
    def geneSn():
        sn = None
        while True:
            sn = time.strftime("%Y%m%d%H%M%S", time.localtime()) + '%s'%random.randint( 0,999 )
            if not Electronic.query.filter_by( sn = sn  ).first():
                break
        return sn

    #  def geneSn():
        #  m = hashlib.md5()
        #  sn = None
        #  while True:
            #  str = "%s-%s"%( int( round( time.time() * 1000) ),random.randint( 0,9999999 ) )
            #  m.update(str.encode("utf-8"))
            #  sn = m.hexdigest()
            #  if not Electronic.query.filter_by( sn = sn  ).first():
                #  break
        #  return sn

    @staticmethod
    def setInStockLog(user_id=0, electronic_id=0, count=0, note=''):
        if user_id < 1:
            return False

        if electronic_id < 1:
            return False

        user_info = User.query.filter_by( id = user_id).first()
        if not user_info:
            return False

        electronic_info = Electronic.query.filter_by( id = electronic_id).first()
        if not electronic_info:
            return False

        log = ElectronicInLog()
        log.user_id= user_id
        log.electronic_id= electronic_id
        log.count = count
        log.note = note
        log.created_time = getCurrentDate()
        db.session.add(log)
        db.session.commit()
        return True

    @staticmethod
    def setOutStockLog(user_id=0, electronic_id=0, count=0, note=''):
        if user_id < 1:
            return False

        if electronic_id < 1:
            return False

        user_info = User.query.filter_by( id = user_id).first()
        if not user_info:
            return False

        electronic_info = Electronic.query.filter_by( id = electronic_id).first()
        if not electronic_info:
            return False

        log = ElectronicInLog()
        log.user_id= user_id
        log.electronic_id= electronic_id
        log.count = count
        log.note = note
        log.created_time = getCurrentDate()
        db.session.add(log)
        db.session.commit()
        return True



